package cn.javaxc.mvcwork.controller;
import cn.javaxc.mvcwork.controller.*;
import cn.javaxc.mvcwork.framework.actions.*;
import cn.javaxc.mvcwork.framework.database.*;
import cn.javaxc.mvcwork.modules.admin.User;
import cn.javaxc.mvcwork.modules.login.*;
import cn.javaxc.mvcwork.modules.site.*;
import cn.javaxc.mvcwork.util.helper.ObjectHelper;
import cn.javaxc.mvcwork.util.common.MSecurityUtils;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.springframework.security.core.userdetails.UserDetails;


public class SecurityHook {

  public final static String fs = System.getProperty("file.separator");


  
  public static Site retrieveSite(ServletContext context, HttpServletRequest request) {
    String serverName = request.getServerName();
    ConnectionPool sqlDriver =(ConnectionPool) context.getAttribute("ConnectionPool");
    MVCConfig prefs = (MVCConfig) context.getAttribute("mvc");
    SiteList sites = SiteUtils.getSiteList(prefs, sqlDriver, serverName);
    if (sites.size() > 0) {
      return (Site) sites.get(0);
    } else {
      if (System.getProperty("DEBUG") != null) {
        System.out.println("SecurityHook-> retrieveSite size: " + sites.size());
      }
    }
    return null;
  }


  
  public static Site retrieveSite(ServletContext context, ConnectionElement ce) {
    ConnectionPool sqlDriver =
        (ConnectionPool) context.getAttribute("ConnectionPool");
    MVCConfig prefs = (MVCConfig) context.getAttribute("mvc");
    SiteList sites = SiteUtils.getSiteList(prefs, sqlDriver, ce);
    if (sites.size() == 1) {
      return (Site) sites.get(0);
    }
    return null;
  }
  public static SystemStatus createSystemStatus(ServletContext context,ConnectionElement ce, String language){
      SystemStatus newSystemStatus = new SystemStatus();
      newSystemStatus.setConnectionElement((ConnectionElement) ce.clone());
      //Store the fileLibrary path for processes like Workflow
      MVCConfig prefs = (MVCConfig) context.getAttribute("mvc");
      // Give the systemStatus a handle to applicationPrefs for language support
      newSystemStatus.setFumineConfig(prefs);
      newSystemStatus.setFileLibraryPath(
          prefs.get("FILELIBRARY") + ce.getDbName() + fs);
      // Use application language setting
      if (language != null) {
        newSystemStatus.setLanguage(language);
      } else {
        // Default to the application's language
        newSystemStatus.setLanguage(prefs.get("SYSTEM.LANGUAGE"));
      }

	  return newSystemStatus;
  }

  public static String portalCheck(ServletContext servletContext, HttpServletRequest request,HttpServletResponse response) {
	retrieveSite(servletContext, request);
      return null;
  }
}
